package pais.www.search;

import java.io.PrintWriter;

import pais.db.HtmlPage;
import pais.db.HtmlPageTable;
import pais.db.Keyword;
import pais.db.KeywordTable;
import papos.rowset.KeyNameNotFoundException;
import papos.rowset.StorageSystem;
import pasys.error.PaposException;


public class Search {
  public static final int RESULT_URL_COUNT = 20;

  public static void printQueryResult(PrintWriter toClient, String query) throws PaposException {
    long uidList[] = new long[RESULT_URL_COUNT];

    KeywordTable keywordTable = KeywordTable.getInstance();
    StorageSystem storage = keywordTable.getStorage();
    Keyword keyword = new Keyword();
    keyword.setKeyword(query);
    try {
      int uidCount = 0;
      if (storage.find("keyword_", keyword)) {
        do {
          if ((uidCount + 1) < RESULT_URL_COUNT) {
            long UID = keyword.getUID();
            boolean duplicatedUID = false;
            // check if the UID is Already Included as a result page
            for (int i = 0; i < uidCount; i++) {
              if (uidList[i] == UID)
                duplicatedUID = true;
            }
            if (!duplicatedUID) {
              uidList[uidCount++] = UID;
            }
          } else {
            break;
          }
        } while (storage.findNext("keyword_", keyword) && 
            keyword.getKeyword().equals(query) );

        for (int uid = 0; uid < uidCount; uid++)
          printPageSummary(toClient, uidList[uid]);

      } else {
        toClient.println("<center>");
        toClient.println("<h3>No pages found with the keyword ( "+query+" )</h3>");

        toClient.println("</center>");
      }
    } catch (KeyNameNotFoundException e) {
      assert(false);
    }
  }


  private static void printPageSummary(PrintWriter toClient, long UID) throws PaposException {
    HtmlPageTable pageTable = HtmlPageTable.getInstance();
    StorageSystem storage = pageTable.getStorage();
    HtmlPage page = new HtmlPage();

    try {
      page.setUID(UID);

      if (storage.find("UID_", page)) {
        toClient.println("<a href="); 
        toClient.println(page.getURL());
        toClient.println(" target=nw >");
        toClient.println(page.getTitle());
        toClient.println("</a><br>");

        toClient.println("(");
        toClient.println(page.getUID());
        toClient.println(")");
        toClient.println(page.getURL());
        toClient.println("<p>");
      } else {
        toClient.println("<p>Internal Server Error. The page with UID="
            + UID + " is not found in db.<p>");
        /*				
				toClient.println("<p>UID index dump =>"
						+ storage.getIndexDump(0) + "<p>");
         */						
      }
    } catch (KeyNameNotFoundException e) {
      assert(false);
    }
  }

}
